from game import zz_game
from zz import zz_log, zz_str, zz_code, zz_dingtalk
from game import game_京东互动游戏
import time
import re

log = zz_log.of()


class Game(game_京东互动游戏.Game):
    def __init__(self, d):
        super().__init__(d)

    def get_name(self):
        return "京东家居馆"

    def task_list_open(self):
        """
        打开任务列表
        """
        self.click_if_exists("打开任务列表", '//*[@text="赚金币"]', '//*[@text="做任务 赚金币"]')
        self.log_msg("已进入任务列表")
        pass

    def task_list_close(self):
        """
        关闭任务列表
        """
        if not self.d.xpath('//*[@text="做任务 赚金币"]').wait(3):
            self.log_msg("未打开任务列表")
            return
        self.click_exists('//*[@text="关闭"]', 3)
        self.log_msg("已关闭任务列表")

    def do50(self):
        self.task_list_open()
        self.task_list_close()
        self.task_list_open()
        self.log_msg("点击签到")
        ok = self.click_exists('//*[@text="立即签到"]')
        if not ok:
            self.log_msg("已签到")
            return True
        alert_ok = self.click_exists('//*[@text="+fHi6dMWPGjBkz0vEHW28jZESYQmAAAAAASUVORK5CYII="]', 2)
        if alert_ok:
            self.log_msg("关闭弹窗")
        while not self.d.xpath('//*[@text="my_cabin_title.2ee4477c"]').wait(2):
            self.log_msg("返回失败-再试")
            self.click_back()
        return True

    def do_task(self):
        """
        开始做任务
        """
        self.task_list_open()
        if not self.d.xpath('//*[@text="去完成"]').wait(2):
            self.log_msg("未找到去完成按钮")
            self.task_list_close()
            return False

        item = self.d.xpath('//*[@text="去完成"]').get(2)
        items = self.d.xpath(item.parent().parent().get_xpath()).child('//android.view.View').all()
        task_items = []
        task_name = None
        for item in items:
            if zz_str.is_null_or_empty(task_name) and str.startswith(item.text, '浏览'):
                task_name = item.text
            if item.text == '去完成' and not zz_str.is_null_or_empty(task_name):
                task_items.append({
                    "task_name": task_name,
                    "task_item": item,
                })
                task_name = None
        timeout = 0
        task_name = ''
        task_item = None
        for task in task_items:
            task_name = task['task_name']
            # print(task_name)
            if str.startswith(task_name, "浏览"):
                match = re.search(r'(\d+)s', task_name)  # 获取浏览x秒
                if match:
                    timeout = match.group(1)
                    task_item = task['task_item']
            # print(task_item)
            if task_item is not None:
                break
        if task_item is None:
            self.log_msg("任务全部完成")
            return True

        self.game_name = task_name
        self.log_msg(f"开始：{task_name}")
        task_item.click()
        self.d.sleep(2.5)
        if self.d.xpath('//*[@text="做任务 赚金币"]').wait(3):
            self.log_msg(f"进入任务失败")
            return False

        self.game_play(int(timeout))
        self.click_back()
        while not self.d.xpath('//*[@text="gold_icon.9cdd3ea0"]').wait(2):
            self.log_msg("返回失败-再试")
            self.click_back()

        return False

    def game_alert(self):
        self.alert_close_by_file('./game/img/京东家居馆')

    def handle_main(self):
        done = self.config_get("jiejv_done")
        if done == 1:
            self.log_msg("京东家居馆-已完成")
            return True
        items = self.d.xpath('//*[@resource-id="com.jingdong.app.mall:id/fl"]').child('android.widget.FrameLayout').all()
        if len(items) < 5:
            self.log_msg("获取底部导航栏失败")
            return
        self.log_msg("点击首页")
        items[0].click()
        self.click_if_exists('点击京东家居馆', '//*[@text="京东家居馆"]', '//*[@text="挑好物逛京东"]')

        self.log_msg("等待进入京东家具馆界面")
        self.d.sleep(2)
        self.game_alert()
        # self.img_click_if_exists_xpath("点击签到有礼", "./game/img/京东家居馆/qiandao_index.png", '//*[@text="gold_icon.9cdd3ea0"]')
        while True:
            if self.d.xpath('//*[@text="gold_icon.9cdd3ea0"]').wait(2):
                self.log_msg("点击签到有礼")
                break
            self.log_msg("点击签到有礼-失败")
            self.d.click(660, 868)

        self.log_msg("已进入京东家具馆界面")
        #
        # 签到
        self.do50()
        #
        while True:
            do_all = self.do_task()
            if do_all:
                break

        self.task_list_close()

        while not self.d.xpath('//*[@resource-id="com.jingdong.app.mall:id/fl"]').wait(2):
            self.log_msg("返回首页失败-再试")
            self.click_back()

        self.config_set("jiejv_done", 1)
        return True
